﻿#include "stream.h"

StreamException::StreamException(const char * msg):std::logic_error(msg)
{
}

StreamDisconnectedException::StreamDisconnectedException(const  char * msg):StreamException(msg)
{
}

InputStream::InputStream()
{
	next = NULL;
	ReadedNum = 0;
}

InputStream::InputStream(InputStream * next):InputStream()
{
	this->next = next;
}

int InputStream::read() throw(StreamException)
{
	unsigned char ret;
	int len = read(&ret, 1);
	if (len != 0) {
		return ret;
	}
	return -1;
}

int InputStream::read(unsigned char * buffer, int readLen)
{
	auto ret = doRead(buffer, readLen);
	ReadedNum += ret;
	return ret;
}

int InputStream::avaliable() const
{
	if (next) {
		return next->avaliable();
	}
	return 0;
}

size_t InputStream::byteReaded() const
{
	return ReadedNum;
}

InputStream * InputStream::GetNext() const
{
	return next;
}

OutputStream::OutputStream()
{
	next = NULL;
}

OutputStream::OutputStream(OutputStream * next)
{
	this->next = next;
}

void OutputStream::write(int val) throw(StreamException)
{
	unsigned char v = val;
	write(&v, 1);
}

void OutputStream::flush()
{
	if (next) {
		next->flush();
	}
}

OutputStream * OutputStream::GetNext()
{
	return next;
}
